var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var debug = require('debug')('ted');
var http = require('http');
var logger = require('log4js').getLogger();
var appconfig = require('./utils/appconfig');


logger.info('开始初始化配置文件 : '+ __dirname + '/cfg.yml');
appconfig.init(require('fs').readFileSync('./cfg.yml', 'utf8'));
var _cfg = appconfig.getCfg();

var routes = require('./routes/route');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');


// app.use(favicon(__dirname + '/public/favicon.ico'));
if(_cfg.env === 'dev'){
    logger.debug('add http request loggger in dev mode');
    app.use(require('morgan')('dev'));    
}

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// if(_cfg.env === 'dev'){
//     app.use('/ted/',function(req, res) {
//         //重定向/ted/**所有请求到index.html
//         res.sendFile(__dirname + '/public/ted/index.html');
//     });
// }


//初始化expressjs的route实例
routes.init(app);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (_cfg.env === 'dev') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});




app.set('port', _cfg.server.port || 3000);
app.set('address', _cfg.server.host || '127.0.0.1');



http.createServer(app).
    listen(app.get('port'),app.get('host'),function(){
        logger.info('server run mode is ' + _cfg.env);
        logger.info('listening at  '+ app.get('port') + ':' + app.get('address'));
});